﻿using EFCore.Models;
using Microsoft.EntityFrameworkCore;
using SIService;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SService
{
    public class OutboundS : OutboundSI
    {
        private readonly WmssystemContext myDb;

        public OutboundS(WmssystemContext myDb)
        {
            this.myDb = myDb;
        }

        public Task<int> Add(PO_Outbound pO_Outbound)
        {
            myDb.PO_Outbound.Add(pO_Outbound);
            return myDb.SaveChangesAsync();
        }

        public async Task<int> CkDel(List<int> Ids)
        {
            // 使用 LINQ 查询语句检索相应的记录
            var detailsToDelete = await myDb.PO_Outbound
                .Where(d => Ids.Contains(d.O_OIndex))
                .ToListAsync();

            // 删除查询结果
            myDb.PO_Outbound.RemoveRange(detailsToDelete);

            // 保存删除操作到数据库
            return await myDb.SaveChangesAsync();
        }

        public async Task<int> CkShen(PO_Outbound pO_Outbound, string to)
        {
            // 1. 根据指定条件查找要审核的记录
            var purchaseOrder = await myDb.PO_Outbound.FindAsync(pO_Outbound.O_OIndex);

            if (purchaseOrder == null)
            {
                // 如果没有找到对应的记录，可以进行适当的处理，比如抛出异常或者返回错误码
                throw new Exception("指定的记录不存在");
            }
            if (to == "通过")
            {
                purchaseOrder.O_OStatus = "已出库";
                //把货品出库的数量回写到入库明细表中
                var ppList = await myDb.PO_Outbounddetails.Where(c => c.O_DOutCode == purchaseOrder.O_ONumber).ToListAsync();
                foreach (var pp in ppList)
                {
                    var ccList = await myDb.PO_Inventorydetails.Where(c => c.I_IProductCode == pp.O_DProductCode).ToListAsync();
                    foreach (var cc in ccList)
                    {
                        cc.I_IYCQuantity = pp.O_DBeforeOutbound;
                        // 如果需要更新其他属性，也可以在这里进行修改
                    }
                }
                //把货品出库的数量回写到回写到销售明细表中
                var ppList1 = await myDb.PO_Outbounddetails.Where(c => c.O_DOutCode == purchaseOrder.O_ONumber).ToListAsync();
                foreach (var pp1 in ppList1)
                {
                    var ccList1 = await myDb.PO_Salesorderdetail.Where(c => c.S_DProductNumber == pp1.O_DProductCode).ToListAsync();
                    foreach (var cc1 in ccList1)
                    {
                        cc1.S_DQuantitySold = (int?)(cc1.S_DQuantitySold - pp1.O_DQuantity);
                        // 如果需要更新其他属性，也可以在这里进行修改
                    }
                }
            }
            else
            {
                purchaseOrder.O_OStatus = "未出库";
            }
            // 2. 更新找到的记录的相应字段
            purchaseOrder.P_OApprover = "admin"; // 以此类推，更新需要修改的字段
            purchaseOrder.P_OApproverTime = DateTime.Now;
            purchaseOrder.P_Reviewcomments = pO_Outbound.P_Reviewcomments;


            // 3. 将更新后的记录保存回数据库中
            myDb.PO_Outbound.Update(purchaseOrder);
            return await myDb.SaveChangesAsync(); // 返回受影响的行数
        }

        public Task<List<PO_Outbound>> Fye(int pageSize, int currentPage, string Number = null, string Type = null, string Status = null, string WName = null)
        {
            var query = myDb.PO_Outbound.AsQueryable();

            // 根据条件进行查询
            if (!string.IsNullOrEmpty(Number))
            {
                query = query.Where(c => c.O_ONumber.Contains(Number.Trim()));
            }
            if (!string.IsNullOrEmpty(Type))
            {
                query = query.Where(c => c.O_OType == Type);
            }
            if (!string.IsNullOrEmpty(Status))
            {
                query = query.Where(c => c.O_OStatus == Status);
            }
            if (!string.IsNullOrEmpty(WName))
            {
                query = query.Where(c => c.O_OWarehouseName == WName);
            }




            // 分页查询
            return query.Skip((currentPage - 1) * pageSize).Take(pageSize).ToListAsync();
        }

        public Task<List<PO_Outbound>> Qu()
        {
            return myDb.PO_Outbound.ToListAsync();
        }

        public async Task<int> Upd(PO_Salesorder pO_Salesorder)
        {
            var existingOrder = await myDb.PO_Salesorder.FirstOrDefaultAsync(o => o.S_OSalesOrder == pO_Salesorder.S_OSalesOrder.Trim());
            // 检查订单是否存在
            if (existingOrder == null)
            {
                return 0; // 表示未找到要更新的订单
            }
            existingOrder.S_ODocumentStatus = pO_Salesorder.S_ODocumentStatus;
            return await myDb.SaveChangesAsync();
        }

        public async Task<int> Upd1(PO_Outbound pO_Outbound)
        {
            var existingOrder = await myDb.PO_Outbound.FirstOrDefaultAsync(o => o.O_OIndex == pO_Outbound.O_OIndex);
            // 检查订单是否存在
            if (existingOrder == null)
            {
                return 0; // 表示未找到要更新的订单
            }
            existingOrder.O_OType = pO_Outbound.O_OType;
            existingOrder.O_OWarehouseName = pO_Outbound.O_OWarehouseName;
            existingOrder.O_ODate = pO_Outbound.O_ODate;
            existingOrder.O_OAssociatedOrderNumber = pO_Outbound.O_OAssociatedOrderNumber;
            existingOrder.O_OCustomerName = pO_Outbound.O_OCustomerName;
            existingOrder.O_OContactPerson = pO_Outbound.O_OContactPerson;
            existingOrder.O_OContactInformation = pO_Outbound.O_OContactInformation;
            existingOrder.O_OAgent = pO_Outbound.O_OAgent;
            existingOrder.O_OReam = pO_Outbound.O_OReam;

            return await myDb.SaveChangesAsync();
        }

        public async Task<List<PO_Salesorder>> Xsqu()
        {
            // 两个表连接查询，并过滤掉 P_OStatus 为 "已出库" 的记录
            var query = from purchaseOrder in myDb.PO_Salesorder
                        join Customer in myDb.Su_Customermanagement
                        on purchaseOrder.S_OCustomerName equals Customer.S_CuNumber.ToString()
                        join Org in myDb.Sys_OrganizationalStructure
                        on purchaseOrder.S_OSalesDepartment equals Org.O_SSerialId.ToString()

                        where purchaseOrder.S_ODocumentStatus != "已出库" && purchaseOrder.S_ODocumentStatus != "未审核"
                        select new PO_Salesorder
                        {
                            S_OCustomerName = Customer.S_CuName,
                            S_OIndex = purchaseOrder.S_OIndex,
                            S_OSalesOrder = purchaseOrder.S_OSalesOrder,
                            S_ODocumentStatus = purchaseOrder.S_ODocumentStatus,
                            S_OSalesDate = purchaseOrder.S_OSalesDate,
                            S_OSalesDepartment = Org.O_SOrganizationName,
                            S_OSalesRepresentative = Customer.S_CuManager,
                            S_OQuantitySold = purchaseOrder.S_OQuantitySold,
                            S_OSalesAmount = purchaseOrder.S_OSalesAmount,
                            S_OContactPerson = purchaseOrder.S_OContactPerson,
                            S_OContactInformation = purchaseOrder.S_OContactInformation,
                            S_OSoldItems = purchaseOrder.S_OSoldItems,
                            S_OCreator = purchaseOrder.S_OCreator,
                            S_ODepartment = purchaseOrder.S_ODepartment,
                            S_OCreationTime = purchaseOrder.S_OCreationTime,
                        };

            var result = await query.ToListAsync();
            return result;
        }

        public async Task<List<PO_Salesorder>> Xsqu1()
        {
            // 两个表连接查询，并过滤掉 P_OStatus 为 "已出库" 的记录
            var query = from purchaseOrder in myDb.PO_Salesorder
                        join Customer in myDb.Su_Customermanagement
                        on purchaseOrder.S_OCustomerName equals Customer.S_CuNumber.ToString()
                        join Org in myDb.Sys_OrganizationalStructure
                        on purchaseOrder.S_OSalesDepartment equals Org.O_SSerialId.ToString()

                        //where purchaseOrder.S_ODocumentStatus == "已出库"
                        select new PO_Salesorder
                        {
                            S_OCustomerName = Customer.S_CuName,
                            S_OIndex = purchaseOrder.S_OIndex,
                            S_OSalesOrder = purchaseOrder.S_OSalesOrder,
                            S_ODocumentStatus = purchaseOrder.S_ODocumentStatus,
                            S_OSalesDate = purchaseOrder.S_OSalesDate,
                            S_OSalesDepartment = Org.O_SOrganizationName,
                            S_OSalesRepresentative = Customer.S_CuManager,
                            S_OQuantitySold = purchaseOrder.S_OQuantitySold,
                            S_OSalesAmount = purchaseOrder.S_OSalesAmount,
                            S_OContactPerson = purchaseOrder.S_OContactPerson,
                            S_OContactInformation = purchaseOrder.S_OContactInformation,
                            S_OSoldItems = purchaseOrder.S_OSoldItems,
                            S_OCreator = purchaseOrder.S_OCreator,
                            S_ODepartment = purchaseOrder.S_ODepartment,
                            S_OCreationTime = purchaseOrder.S_OCreationTime,
                        };

            var result = await query.ToListAsync();
            return result;
        }
    }
}
